// pages/upload/upload.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    text: "",
    videos: [],
    name: ""
  },

  /**
   * 
   */
  contentChange(e){
    // console.log(e);
    this.setData({
      text: e.detail.value
    })
  },

  /**
   * 上传视频预览
   */
  afterRead:function(e) {
    // console.log(e);
    const { file } = e.detail;
    const{fileList=[]} = this.data;
    fileList.push({
      url:file.url,
      isVideo: true
    });
    this.setData({
      fileList
    })
    // console.log(getApp().globalData.id);
  },

  /**
   * 上传视频到云
   */
  uploadToCloud() {
    wx.cloud.init();
    const { fileList } = this.data;
    if (!fileList.length) {
      wx.showToast({ title: '请选择视频', icon: 'none' });
    } else {
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`${getApp().globalData.id}${new Date().getTime()}.mp4`, file));
      Promise.all(uploadTasks)
      .then(data => {
        wx.showToast({ title: '上传成功', icon: 'success' });
        const newFileList = data.map(item => { url: item.fileID });
        this.setData({ fileList: newFileList });
        // console.log(data[0].fileID);
        let obj = {}
        obj.name = this.data.name
        obj.videoUrl = data[0].fileID
        obj.text = this.data.text
        obj.commentNum = 0
        obj.up = 0
        // obj.showFocus = true
        obj.id = getApp().globalData.id
        obj.passtime = new Date().getTime()/1000
        obj.header = this.data.header
        wx.cloud.callFunction({
          name: "updateVideoData",
          data: {
            // id: getApp().globalData.id,
            obj: obj,
            action: "add"
          },
          success: res=>{
            wx.switchTab({
              url: '/pages/video/video'
            })
          }
        })
      })
      .catch(e => {
        wx.showToast({ title: '上传失败', icon: 'none' });
        console.log(e);
      });
    }
  },
  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(getApp().globalData.id);
    const {videos,name,header} = options
    this.setData({
      videos,
      name,
      header
    })

    // console.log(options.videos);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})